<template>
  <div>
    <a-modal v-model="showModal" @ok="confirmOk" @cancel="cancel" :title="titles" width="70%">
      <a-spin :spinning="loading">
        <a-form :form="form">
          <a-row :gutter="[24, 0]">
            <a-col :span="12">
              <a-form-item class="mb-15" label="昵称" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-input placeholder="请输入" v-decorator="[
                  'memberNickname',
                  {
                    rules: [{ required: true, message: '请输入', whitespace: true }],
                  },
                ]" maxLength="30"></a-input>
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item class="mb-15" label="手机号" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-input placeholder="请输入" v-decorator="[
                  'mobile',
                  {
                    rules: [{ required: true, message: '请输入', whitespace: true }],
                  },
                ]" maxLength="30"></a-input>
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="[24, 0]">
            <a-col :span="12">
              <a-form-item class="mb-15" label="标题" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-input placeholder="请输入" v-decorator="[
                  'title',
                  {
                    rules: [{ required: true, message: '请输入', whitespace: true }],
                  },
                ]" maxLength="30"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item class="mb-15" label="地址" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-input placeholder="请输入" v-decorator="[
                  'address',
                  {
                    rules: [{ required: true, message: '请输入', whitespace: true }],
                  },
                ]" maxLength="30"></a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item class="mb-15" label="发布状态" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-switch @change="checkedChange" v-decorator="['publishStatus', { valuePropName: 'checked' }]"
                  :checkedValue="0" :unCheckedValue="1" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item class="mb-15" label="类别" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-select class="flex-1" @change="changeSelect" placeholder="请选择" v-decorator="['categoryCode']">
                  <a-select-option :value="item.categoryCode" v-for="(item, index) in list">{{ item.categoryName
                    }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="[24]">
            <a-col :span="24">
              <a-tabs :defaultActiveKey="tabsId" @change="callback" style="width: 33.33%;">
                <a-tab-pane key="1" tab="图片">
                  <a-form-item class="mb-15" label="图片" :label-col="labelCol" :wrapper-col="wrapperCol">
                    <PreviewImage :showUpload="isShow" class="mt-12" :is-preview="false" :scene="1"
                      :show-upload="formgetFileLength(`picUrl`) < 1" @uploadSuccess="formuploadSuccess($event, `urls`)"
                      accept=".png,.jpg" :maxCount="1" v-decorator="[`urls`, { initialValue: [] }]" />
                  </a-form-item>
                </a-tab-pane>
                <a-tab-pane key="2" tab="视频" force-render>
                  <a-form-item class='mb-15' label='视频' :label-col='labelCol' :wrapper-col='wrapperCol'>
                    <a-upload @change='videoChange' :before-upload='beforeUpload' :showUploadList='false'
                      action='http://cwqd.ricecs.cn/admin-api/system/file/upload' :headers='{ Authorization: token }'
                      accept=".mp4">
                      <a-button>
                        <a-icon type='upload' />
                        上传
                      </a-button>
                    </a-upload>
                    <video :src='videoUrl' style='width: 100%;height: 120px' controls></video>
                  </a-form-item>
                </a-tab-pane>
              </a-tabs>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="24">
              <quill-editor class="editor" v-model="content" ref="myQuillEditor" :options="editorOption"
                @blur="onEditorBlur($event)" @focus="onEditorFocus($event)" @change="onEditorChange($event)"
                @ready="onEditorReady($event)">
              </quill-editor>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>
    </a-modal>
  </div>
</template>
<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { get } from 'lodash'
import { deductionDetail, trendsSave, trendsAdd } from '@/api/newPet'
import { isNullorEmpty } from '@/utils/util'
import storage from '@/utils/storage'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import {
  cateList
} from '@/api/index'
export default {
  data() {
    return {
      videoUrl: '',
      token: '',
      list: [],
      status: true,
      loading: false,
      isShow: true,
      labelCol: {
        span: 3,
      },
      content: '<p>Hello World!</p>',
      editorOption: {
        placeholder: '请输入',
        theme: 'snow',
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
              ['blockquote', 'code-block'], // 引用  代码块
              [{ header: 1 }, { header: 2 }], // 1、2 级标题
              [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
              [{ script: 'sub' }, { script: 'super' }], // 上标/下标
              [{ indent: '-1' }, { indent: '+1' }], // 缩进
              // [{ direction: 'rtl' }], // 文本方向
              [{ size: ['12', '14', '16', '18', '20', '22', '24', '28', '32', '36'] }], // 字体大小
              [{ header: [1, 2, 3, 4, 5, 6] }], // 标题
              [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
              // [{ font: ['songti'] }], // 字体种类
              [{ align: [] }], // 对齐方式
              ['clean'], // 清除文本格式
              ['image'], // 链接、图片，需要视频的可以加上video
            ],
          },
        },
      },
      data: [
        { name: '规格1', img: '', num: 1, price: 0 },
        { name: '规格1', img: '', num: 1, price: 0 },
      ],
      columns: [
        { title: '规格名称', dataIndex: 'name', align: 'center', width: 140, scopedSlots: { customRender: 'name' } },
        {
          title: '规格图片',
          dataIndex: 'img',
          width: 120,
          align: 'center',
          scopedSlots: { customRender: 'img' },
        },
        { title: '规格库存', dataIndex: 'num', align: 'center', width: 70, scopedSlots: { customRender: 'num' } },
        {
          title: '规格价格（元）',
          dataIndex: 'price',
          align: 'center',
          width: 70,
          scopedSlots: { customRender: 'price' },
        },
        {
          title: '老用户专享最高可售库存',
          dataIndex: 'msNum',
          align: 'center',
          width: 110,
          scopedSlots: { customRender: 'price' },
        },
        {
          title: '老用户最低价格（元）',
          dataIndex: 'msPrice',
          align: 'center',
          width: 110,
          scopedSlots: { customRender: 'price' },
        },
        {
          title: '操作',
          fixed: 'right',
          dataIndex: 'action',
          width: 110,
          scopedSlots: { customRender: 'action' },
          align: 'center',
        },
      ],

      wrapperCol: {
        span: 16,
      },
      details: {},
      showModal: false,
      titles: '发布',
      info: {},
      form: this.$form.createForm(this),
      tabsId: '1'
    }
  },
  computed: {},
  watch: {},
  async created() {
    this.token = storage.get(ACCESS_TOKEN)
    this.getList()
  },
  components: {
    quillEditor,
  },
  methods: {
    getList() {
      cateList({ pageNo: 1, pageSize: 10, scope: 3 }).then(data => {
        this.list = data.list
      })
    },
    callback(key) {
      this.tabsId = key
    },
    //视频
    videoChange(info) {
      let _this = this
      let fileList = [...info.fileList]

      // 1. Limit the number of uploaded files
      //    Only to show two recent uploaded files, and old ones will be replaced by the new
      fileList = fileList.slice(-1)

      // 2. read from response and show file link
      fileList = fileList.map((file) => {
        if (file.response) {
          // Component will show file.url as link
          _this.videoUrl = file.response.data
        }
      })
    },
    beforeUpload(file) {
      console.log(file)
      const isLt500KB = file.size / 1024 / 1024 < 100
      let isVideo = true
      if (!isLt500KB) {
        this.$message.error('上传的文件大小不能超过 100mb!')
        return false
      }
      if (file.type != 'video/mp4') {
        this.$message.error('请上传视频文件')
        return false
      }
      return true
    },
    onEditorBlur(quill) {
      console.log('editor blur!', quill)
    },
    // 获得焦点事件
    onEditorFocus(quill) {
      console.log('editor focus!', quill)
    },
    // 准备富文本编辑器
    onEditorReady(quill) {
      console.log('editor ready!', quill)
    },
    // 内容改变事件，只需要这一个方法就够了
    onEditorChange({ quill, html, text }) {
      console.log('editor change!', quill, html, text)
      this.content = html
    },
    formgetFileLength(type) {
      //获取图片
      return get(this.form.getFieldValue(type), 'length') || 0
    },

    formuploadSuccess(data, type) {
      this.form.setFieldsValue({
        [type]: [...this.form.getFieldValue(type), data.path],
      })
    },
    checkedChange(e) {
      this.form.setFieldsValue({
        publishStatus: e == true ? 1 : 0
      })
    },
    changeSelect(e) {
      this.form.setFieldsValue({
        secondCategoryCode: e,
      })
    },
    cancel() {
      this.form.resetFields()
      this.showModal = false
      this.status = true
      this.tabsId = '1'
    },
    confirmOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          // this.loading = true
          const { info } = this
          // console.log(info,"info");
          if (values.time) {
            values.timeStart = this.$utils.getStartTime(values.time[0])
            values.timeEnd = this.$utils.getEndTime(values.time[1])
          }
          let data = {
            id: info && info.id ? info.id : undefined,
            ...this.$utils.trimValue(values),
            isEnabled: typeof values.isEnabled === 'undefined' ? true : values.isEnabled,
            publishStatus: values.publishStatus == true ? 1 : 0,
            secondCategoryCode: values.categoryCode,
            // urls: this.tabsId == '1' ? values.urls : '',
            // videoUrl: this.tabsId == '2' ? this.videoUrl : ''
            urls: values.urls,
            videoUrl: this.videoUrl
          }
          data.urls = data.urls.toString()
          const fun = info && info.id ? trendsSave : trendsAdd
          fun(data)
            .then(() => {
              this.$message.success(info && info.id ? '修改成功！' : '新增成功！')
              this.$emit('upload')
              this.cancel()
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
    getData() {
      this.loading = true
      deductionDetail({ id: 1 })
        .then((data) => {
          this.details = data
        })
        .finally(() => (this.loading = false))
    },
    open(data) {
      this.info = data
      if (isNullorEmpty(data)) {
        this.titles = '发布'
      } else {
        this.titles = '编辑'
        this.content = data.content
        if (!isNullorEmpty(data.videoUrl)) {
          if (data.videoUrl.split(' ').length != 0) {
            this.videoUrl = data.videoUrl.split(' ')
          }
        }
      }
      this.$nextTick(() => {
        this.form.setFieldsValue({
          ...data,
          urls: data.urls.split(','),
          categoryCode: data.secondCategoryCode,
        })
      })
      this.showModal = true
      // images:['https://img2.baidu.com/it/u=1906732828,3160455141&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=666']
      this.$nextTick(() => {
        this.form.setFieldsValue({
          isEnabled: true,
        })
      })
      this.$emit('upload')
    },
  },
}
</script>
<style lang="less" scoped>
/deep/ .ant-form-item-label {
  // width: 100px;
}
</style>
